import React, { Component } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { connect } from 'dva';
import { Card, Button, Form, Input, Select, DatePicker, Popconfirm, Spin } from 'antd';
import MyPageTable from '@/components/MyPageTable';
import { onTableData } from '@/utils/utils.js';
import CopyToClipboard from '@/components/CopyToClipboard';
import moment from 'moment';
const { Option } = Select;
const { RangePicker } = DatePicker;
import { router } from 'umi';
import { getTimeDistance } from '@/utils/utils';
@connect(({ order, loading }) => ({
  ...order,
  loading: loading.effects['order/queryPendingOrderClosureList'],
}))
@Form.create()
export default class HomePage extends Component {
  state = {
    current: 1,
    datas: {},
    yunTime: getTimeDistance('month'),
  };
  componentDidMount() {
    this.props.dispatch({
      type: 'order/PlateformChannel',
    });
    this.onList(1, 10);
  }
  onList = (pageNumber, pageSize, data = {}) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'order/queryPendingOrderClosureList',
      payload: {
        pageSize,
        pageNumber,
        ...data,
        status: (data && data.status) || '04',
      },
    });
  };
  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      console.log('Received values of form: ', values);
      if (values.createDate && values.createDate.length < 1) {
        values.createTimeStart = '';
        values.createTimeEnd = '';
        this.setState(
          {
            datas: { ...values },
          },
          () => {
            this.onList(1, 10, { ...values });
          },
        );
      } else if (values.createDate) {
        values.createTimeStart = moment(values.createDate[0]).format('YYYY-MM-DD HH:mm:ss');
        values.createTimeEnd = moment(values.createDate[1]).format('YYYY-MM-DD HH:mm:ss');
        this.setState(
          {
            datas: { ...values },
          },
          () => {
            this.onList(1, 10, { ...values });
          },
        );
      } else {
        this.setState(
          {
            datas: { ...values },
          },
          () => {
            this.onList(1, 10, { ...values });
          },
        );
      }
    });
  };
  //table 页数
  onPage = e => {
    this.setState(
      {
        current: e.current,
      },
      () => {
        this.onList(e.current, 10, this.state.datas);
      },
    );
  };
  confirm = e => {
    this.props.dispatch({
      type: 'order/closeUserOrderAndRefundPrice',
      payload: {
        orderId: e,
      },
      callback: res => {
        this.onList(this.state.current, 10, this.state.datas);
      },
    });
  };
  onexport = () => {
    const { yunTime } = this.state;
    if (this.props.form.getFieldValue('createDate')) {
      this.props.dispatch({
        type: 'order/exportOpeAllUserOrders',
        payload: {
          createTimeEnd: moment(this.props.form.getFieldValue('createDate')[1]).format(
            'YYYY-MM-DD HH:mm:ss',
          ),
          createTimeStart: moment(this.props.form.getFieldValue('createDate')[0]).format(
            'YYYY-MM-DD HH:mm:ss',
          ),
        },
      });
    } else {
      this.props.dispatch({
        type: 'order/exportOpeAllUserOrders',
        payload: {
          createTimeEnd: moment(yunTime[1]).format('YYYY-MM-DD HH:mm:ss'),
          createTimeStart: moment(yunTime[0]).format('YYYY-MM-DD HH:mm:ss'),
        },
      });
    }
  };
  render() {
    const { closeList, closeTotal, loading, PlateformList } = this.props;
    const paginationProps = {
      current: this.state.current,
      pageSize: 10,
      total: closeTotal,
      showTotal: total => (
        <span style={{ fontSize: '14px' }}>
          <span>共{Math.ceil(total / 10)}页</span>&emsp;
          <span>共{total}条</span>
        </span>
      ),
    };
    let detailsStute = {
      '01': '待支付',
      '02': '支付中',
      '03': '已支付申请关单',
      '04': '待发货',
      '05': '待确认收货',
      '06': '租用中',
      '07': '待结算',
      '08': '结算待支付',
      '09': '订单完成',
      '10': '交易关闭',
    };
    const columns = [
      {
        title: '订单编号',
        dataIndex: 'orderId',
        render: orderId => <CopyToClipboard text={orderId} />,
        width: '10%',
      },
      {
        title: '店铺名称',
        dataIndex: 'shopName',
        width: '10%',
      },
      {
        title: '渠道来源',
        dataIndex: 'channelName',
        width: '10%',
      },
      {
        title: '商品名称',
        dataIndex: 'productName',
        width: '10%',
      },
      {
        title: '当前租期',
        dataIndex: 'currentPeriods',
        width: '10%',
      },
      {
        title: '已付押金',
        dataIndex: 'deposit',
        width: '10%',
      },
      {
        title: '已付租金',
        dataIndex: 'payedRentAmount',
        width: '10%',
      },
      {
        title: '应退金额',
        dataIndex: 'refundAmount',
        width: '10%',
      },
      {
        title: '退款状态',
        width: '10%',
        render: (text, record) => <span>{record.refundStatus ? '已退款' : '未退款'}</span>,
      },
      {
        title: '订单状态',
        dataIndex: 'status',
        width: '10%',
        render: status => {
          return <span>{detailsStute[status]}</span>;
        },
      },
      {
        title: '操作',
        width: '10%',
        align: 'center',
        render: e => {
          return (
            <div style={{ textAlign: 'center' }}>
              <div
                className="primary-color"
                onClick={() => router.push(`/Order/Details?id=${e.orderId}`)}
              >
                查看
              </div>
              {e && e.status === '04' ? (
                <Popconfirm
                  placement="top"
                  title={'确定要关闭订单并退款吗？'}
                  onConfirm={() => this.confirm(e.orderId)}
                  okText="确定"
                  cancelText="取消"
                >
                  <Button type="link">订单关闭并退款</Button>
                </Popconfirm>
              ) : (
                <Button type="link" disabled>
                  订单关闭并退款
                </Button>
              )}
            </div>
          );
        },
      },
    ];
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };

    return (
      <PageHeaderWrapper>
        <Card bordered={false}>
          <Form layout="inline" onSubmit={this.handleSubmit}>
            <Form.Item>
              {getFieldDecorator('productName', {})(<Input placeholder="请输入商品名称" />)}
            </Form.Item>
            {/* <Form.Item>
              {getFieldDecorator(
                'channelId',
                {},
              )(
                <Select placeholder="渠道来源" style={{ width: 180 }}>
                  <Option value="">全部</Option>

                  {PlateformList.map((item, val) => {
                    return (
                      <Option value={item.channelId} key={val}>
                        {item.channelName}
                      </Option>
                    );
                  })}
                </Select>,
              )}
            </Form.Item> */}
            <Form.Item>
              {getFieldDecorator('userName', {})(<Input placeholder="请输入下单人姓名" />)}
            </Form.Item>
            <Form.Item>
              {getFieldDecorator('telephone', {})(<Input placeholder="请输入下单人手机号" />)}
            </Form.Item>
            <div>
              <Form.Item>
                <Button type="primary" htmlType="submit">
                  查询
                </Button>
              </Form.Item>
              <Form.Item>
                <Button onClick={this.onexport}>导出</Button>
              </Form.Item>
            </div>
            <Form.Item>
              {getFieldDecorator('orderId', {})(<Input placeholder="请输入订单编号" />)}
            </Form.Item>
            <Form.Item>
              {getFieldDecorator('shopName', {})(<Input placeholder="请输入店铺名称" />)}
            </Form.Item>
            <Form.Item>{getFieldDecorator('createDate', {})(<RangePicker />)}</Form.Item>
            <Form.Item>
              {getFieldDecorator('status', { initialValue: '04' })(
                <Select placeholder="订单状态" style={{ width: 180 }}>
                  <Option value="04">待发货</Option>
                  <Option value="10">交易关闭</Option>
                </Select>,
              )}
            </Form.Item>
          </Form>

          <Spin spinning={loading}>
            <MyPageTable
              onPage={this.onPage}
              paginationProps={paginationProps}
              dataSource={onTableData(closeList)}
              columns={columns}
            />
          </Spin>
        </Card>
      </PageHeaderWrapper>
    );
  }
}
